package com.example.miuicolorpick

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View


class MiColorPickView : View {

    var mWidth: Int = 0
    val mPain = Paint()

    var miColorView: MiColorView? = null

    var state: State = State.None

    @JvmOverloads
    constructor(
        context: Context,
        attributeSet: AttributeSet? = null,
        defStyleAttr: Int = 0
    ) : super(context, attributeSet, defStyleAttr) {
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mWidth = w
        DrawHelper.totalWidth = mWidth
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if (canvas != null) {
            DrawHelper.drawBottom(canvas, mPain)
            if (state == State.BottomState) {
                DrawHelper.drawTopBar(canvas, mPain)
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {

        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                DrawHelper.miColors.forEachIndexed { index, miColor ->
                    if (ViewUtil.isInViewArea(miColor.rectBottom, event.x, event.y)) {
                        miColorView?.onBottomColorClick(miColor.mainColor)
                        state = State.BottomState
                        DrawHelper.curIndex = index
                        invalidate()
                    }
                }
            }
        }
        return true
    }
}